<?php

class C_logon extends CI_Controller {

	public function index(){
		//Loading functions for fom handling.
		$this->load->helper('form');
		$this->load->library('form_validation');
		
		//Loading basic templates.
		$this->load->view('templates/v_header');
		$this->load->view('templates/v_menu_basic');
		
		//Setting the delimiters for error messages so they can be styled by CSS.
		$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
		 
		//Setting the form validation rules.
		$this->form_validation->set_rules('username', 'Username', 'required');
		$this->form_validation->set_rules('password', 'Password', 'required');
		
		//Resetting login error message.
		$view_data['login_error'] = '';
		
		//Validating data input.
		if ($this->form_validation->run()){
			//Creating an user object.
			$this->load->model('m_user', 'user');
			
			//Getting the entered password and username.
			$password = $this->input->post('password');
			$username = $this->input->post('username');
			
			//Trying to login user.
			if ($this->user->login($username, $password)) {
				redirect('c_start'); //If loged in, redirect to start page.
			}
			else {
				//Setting error messages for incorrect user information.
				$view_data['login_error'] = '<p class="error">Incorrect username or password.</p>';
			}
		}
		
		//Repopulating the form.
		$view_data['entered_username'] = set_value('username');
		
		//If not valid, load login page.
		$this->load->view('pages/v_logon', $view_data);
		
		//Loading footer.
		$this->load->view('templates/v_footer');
	}
}
?>